# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(optparse)
library(grid)
library(cowplot)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "Class_Color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote)) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleColDf <- read_tsv(opt$sc) %>%
  select(c("ClassNote", "col"))

sampleCols <- sampleColDf %>%
  deframe()

groups <- unique(sampleInfo$ClassNote)

parent <- "./"
fileName <- paste0(parent, "/AllMet_Test.csv")
outFileName <- paste0(parent, "/AllMet_Boxplot_with_Points.pdf")

pValueData <- read.csv(fileName, header = T, stringsAsFactors = F, comment.char = "") %>%
  arrange(P)

names <- pValueData$Metabolite

data <- read_tsv(opt$i) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  filter(ClassNote %in% groups)

head(data)
head(pValueData)

getP <- function(name) {
  pData <- data %>% filter(Metabolite == name)
  pValueDf <- pValueData %>% filter(Metabolite == name)
  p <- ggplot(pData, mapping = aes(x = ClassNote, y = Value, fill = ClassNote)) +
    theme_bw(base_size = 8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 8, vjust = 0.5),
          axis.text.y = element_text(size = 8), legend.position = 'none',
          axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
          legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 8),
          panel.border = element_rect(size = 0.25)
    ) +
    xlab("") +
    ylab("") +
    ggtitle(paste0(pValueDf$Metabolite, "\n", "P=", scientific(pValueDf$P, 2))) +
    scale_fill_manual("", values = sampleCols) +
    stat_boxplot(geom = "errorbar", width = 0.5) +
    geom_boxplot(outlier.shape = NA) +
    geom_jitter(size = 0.75)
  return(p)
}

p <- names %>%
  map(getP)

print("in")

pdf(outFileName, 7.5, 9)

for (i in seq(1, length(p), 9)) {
  plot.new()
  iEnd <- i + 8
  inP <- p[i:iEnd] %>%
    map(function(x) {
      if (is.null(x)) {
        p <- ggplot() + theme_void()
        p
      }else x
    })
  inEnd <- if (length(inP) < 3) {
    length(inP)
  }else 3
  inP[1:inEnd] = inP[1:inEnd] %>%
    map(~.x + theme(plot.margin = margin(t = 0.5, unit = "cm")))
  ggarrange(plots = inP, ncol = 3, newpage = F)
}

dev.off()
